package com.itheima.tliasmanagementspringboot.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.itheima.tliasmanagementspringboot.properties.AliYunOSSProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * 阿里云OSS操作工具类
 */
@Component
public class AliYunOSSUtils {

    @Autowired
    AliYunOSSProperties aliYunOSSProperties;

    public  String upload2OSS(MultipartFile image) {

        //1. 生成uuid文件名（防止文件名重复被覆盖）
        //获取原始文件名
        String originalFilename = image.getOriginalFilename(); //abc.efg.jpg
        //截取原始文件名的后缀
        //取出后缀(格式)
        String suffix = "";
        int index = originalFilename.lastIndexOf(".");
        if (index != -1) {//健壮性判断,避免文件没有后缀的情况
            suffix = originalFilename.substring(index);
        }
        /*String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")); // .jpg*/
        //生成唯一的UUID文件名
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如 exampleobject.txt。
        String objectName = UUID.randomUUID().toString() + suffix;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(aliYunOSSProperties.getEndpoint(), aliYunOSSProperties.getAccessKeyId(), aliYunOSSProperties.getAccessKeySecret());
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(aliYunOSSProperties.getBucketName(), objectName, image.getInputStream());
            // 上传文件。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (Exception ce) {
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        //文件访问路径(阿里云上的文件的url地址)
        return aliYunOSSProperties.getEndpoint().split("//")[0] + "//" + aliYunOSSProperties.getBucketName() + "." + aliYunOSSProperties.getEndpoint().split("//")[1] + "/" + objectName;
    }
}
